import {history, useDispatch, connect, useModel} from 'umi'
import {Row, Col, Form, Button, Input, Space, Upload, message} from 'antd'
import React, {useEffect, useState} from 'react'
import {useLocation} from 'react-router'
import {FormTime, FormInput} from '@/components/SearchForm/SearchFormItem'
import {uploadFileUrl} from '@/service/common/upload'
import styles from './index.less'
import cardStyles from '../index.less'
import {orderValidateCar} from '@/service/order'
import {formatDate} from '@/utils/common/dateFilter'

const formLayout = {
	labelCol: {
		xs: {span: 24},
		sm: {span: 4},
	},
	wrapperCol: {
		xs: {span: 24, offset: 0},
		sm: {span: 12, offset: 0},
	},
}
function CheckCar(props: any) {
	const {
		global: {currentRoute},
	} = props
	const [orderIds, setOrderIds] = useState('')
	const [fileList, setFileList] = useState<any>([])
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [loading, setLoading] = useState(false)
	// 获取路由中订单编号
	const location = useLocation()
	const routerName = () => {
		setOrderIds(location?.search?.split('id=')[1])
	}
	const [form] = Form.useForm()
	useEffect(() => {
		routerName()
	}, [orderIds])
	const dispatch = useDispatch()
	// 返回订单列表
	const onCancel = () => {
		dispatch({
			type: 'global/deleteTabs',
			payload: currentRoute,
		})
		history.goBack()
	}
	const onFinish = (values: any) => {
		// setLoading(true)
		// 默认验车类型为交车（1==交车，2==还车）
		const data = {...values}
		data.validateType = 1
		data.validateTime = formatDate(
			values.validateTime,
			'YYYY-MM-DD HH:mm:ss',
		)
		orderValidateCar(orderIds, data).then((res) => {
		  if (res.success) {
		    setLoading(false)
		    onCancel();
		  }
		});
	}

	const onFinishFailed = (errorInfo: any) => errorInfo

	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}
	//  文件上传生成上传信息
	const uploadProps = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file 测试上传:files
		data: {
			modelName: 'carOrder',
			targetAttr: 1,
		},
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
				const list: any = []
				info?.fileList?.forEach((res: any) => {
					list.push(res?.response?.data.id)
				})
				form.setFieldsValue({attachmentList: list})
			}
			setFileList(info?.fileList)
		},
		onRemove(info: any) {
			form.setFieldValue('attachmentList', '')
			message.success(`${info?.name}移除成功`)
		},
		fileList,
	}
	return (
		<div className={cardStyles.card} id="checkCarInfo">
			<p className={cardStyles.title}>验车信息</p>
			<div className={styles.form}>
				<Form
					form={form}
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete="off"
					{...formLayout}>
					<Row gutter={24} className={cardStyles.rows}>
						<Col span={24}>
							<FormInput
								name="validatePerson"
								label="验车人员"
								placeholder="请填写验车人员"
								rules={[
									{required: true, message: '请填写验车人员'},
								]}
								style={{width: '300px'}}
							/>
						</Col>
						<Col span={24}>
							<FormTime
								subtype="date"
								name="validateTime"
								label="验车时间"
								rules={[
									{required: true, message: '请选择验车时间'},
								]}
								style={{width: '300px'}}
							/>
						</Col>
						<Col span={24}>
							<Form.Item name="remark" label="备注">
								<Input
									maxLength={200}
									placeholder="请填写绑车备注信息，不超过200个字符"
									allowClear
									style={{width: '600px'}}
								/>
							</Form.Item>
						</Col>
						<Col span={24}>
							<Form.Item
								label="验车清单上传"
								name="attachmentList"
								valuePropName="fileList"
								getValueFromEvent={normFile}
								className={styles.fileUpload}
								rules={[
									{required: true, message: '请上传验车清单'},
								]}>
								<Upload {...uploadProps}>
									{fileList?.length >= 5 ? null : (
										<Button>请选择文件</Button>
									)}
								</Upload>

								<p style={{margin: '15px 0 0 0'}}>
									清单说明：附件最大支持200M，
								</p>
								<p>支持格式：PDF、Word、Excel、JPG、PNG</p>
							</Form.Item>
						</Col>
					</Row>
					<Row justify="center" style={{marginTop: '20px'}}>
						<Form.Item>
							<Space>
								<Button shape="round" onClick={onCancel}>
									取消
								</Button>
								<Button
									shape="round"
									type="primary"
									htmlType="submit"
									loading={loading}>
									提交
								</Button>
							</Space>
						</Form.Item>
					</Row>
				</Form>
			</div>
		</div>
	)
}
export default connect(({order: {details}, global}: any) => ({
	orderId: details.id,
	global,
}))(CheckCar)
